package com.monas.server.parser.linux;

import java.sql.Types;
import java.util.LinkedList;

import com.monas.server.parser.MonasHeader;
import com.monas.server.parser.MonasParser;

/**
 * 
 * @author eko wahyudi
 * 
 */
public class Cpu extends MonasParser {

	public Cpu() {
		super(new MonasHeader(Types.FLOAT, "cpu_used"), new MonasHeader(
				Types.FLOAT, "cpu_system"), new MonasHeader(Types.FLOAT,
				"cpu_ni"), new MonasHeader(Types.FLOAT, "cpu_idle"),
				new MonasHeader(Types.FLOAT, "cpu_wa"), new MonasHeader(
						Types.FLOAT, "cpu_hi"), new MonasHeader(Types.FLOAT,
						"cpu_si"), new MonasHeader(Types.FLOAT, "cpu_st"));
	}

	@Override
	public boolean isNextBegin(String line) {
		return line.indexOf("grep Cpu") > 0;
	}

	@Override
	public boolean isFinish(String line) {
		return line.indexOf("Cpu") == -1;
	}

	@Override
	public String getTableName() {
		return "cpu";
	}

	@Override
	public LinkedList<Object[]> getRecords() {
		LinkedList<Object[]> records = new LinkedList<Object[]>();
		if (getLines().size() > 0) {
			for (String line : getLines()) {
				if (line.indexOf("Cpu") >= 0) {
					line = filter(line);
					String[] fields = line.split("\\s+");
					String[] objects = { getValue(fields[1]),
							getValue(fields[2]), getValue(fields[3]),
							getValue(fields[4]), getValue(fields[5]),
							getValue(fields[6]), getValue(fields[7]),
							getValue(fields[8]) };
					records.add(objects);
					break;
				}
			}
		}
		return records;
	}

	private String filter(String line) {
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < line.length(); i++) {
			char ch = line.charAt(i);

			builder.append(ch);

			remove(builder, "[m");
			remove(builder, "[K");
		}
		return builder.toString();
	}

	private void remove(StringBuilder builder, String text) {
		if (builder.toString().endsWith(text)) {
			builder.delete(builder.length() - text.length(), builder.length());
		}
	}

	private String getValue(String field) {
		int idx = field.indexOf("%");
		return field.substring(0, idx);
	}

}
